import json
import os
import re
import shutil
from datetime import time
from venv import logger

from django.conf import settings
from django.core.paginator import Paginator
from django.core.serializers import serialize
from django.db import transaction
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
import xlrd

from domainManager import models
from domainManager.models import DomainDate, DomainUrl


def index(request):
    path = "jession.json"
    file = open(path, "rb")
    fileJson = json.load(file)
    fields = fileJson["data"]

    # futures = fileJson("futures")
    # type = fileJson("type")
    # name = fileJson("name")
    # time = fileJson("time")

    print(type(fields))
    for i in range(0, len(fields)):
        domain = fields[i]
        # print(domain)
        srcIp = domain.get('srcIp')
        firstPacket = domain.get('firstPacket')
        totDataBytes = domain.get('totDataBytes')
        srcPort = domain.get('srcPort')
        totPackets = domain.get('totPackets')
        ipProtocol = domain.get('ipProtocol')
        node = domain.get('node')
        lastPacket = domain.get('lastPacket')
        dstPort = domain.get('dstPort')
        totBytes = domain.get('totBytes')
        dstIp = domain.get('dstIp')
        srcGEO = domain.get('srcGEO')
        id = domain.get('id')
        fileId = domain.get('fileId')
        # print(fileId)
        uri = domain.get('http.uri')
        if uri != None:
            result = re.findall(".*%s(.*)%s.*" % ("'", ".com"), uri)
        if result:
            print(result)
        else:
            print("---------没有值")

        domainDate = DomainDate()

        domainDate.originalId = id
        domainDate.srcIp = srcIp
        domainDate.firstPacket = firstPacket
        domainDate.totDataBytes = totDataBytes
        domainDate.srcPort = srcPort
        domainDate.totPackets = totPackets
        domainDate.ipProtocol = ipProtocol
        domainDate.node = node
        domainDate.lastPacket = lastPacket
        domainDate.dstPort = dstPort
        domainDate.totBytes = totBytes
        domainDate.dstIp = dstIp
        domainDate.srcGEO = srcGEO
        domainDate.uri = uri
        domainDate.fileId = fileId

        # print(domainDate)

        domainDate.save()

    return render(request, 'domainManager/index.html')


def domainList(request):
    data = {'status': 0, 'rlist': "fsssfaf", "blist": "23323"}

    return render(request, 'domainManager/domainList.html', {"d": json.dumps(data, ensure_ascii=False)})


def domainUrlList(request):
    data = {'status': 0, 'rlist': "fsssfaf", "blist": "23323"}

    return render(request, 'domainManager/domainUrlList.html', {"d": json.dumps(data, ensure_ascii=False)})


def admin(request):
    print("12321331---------")

    data = {'status': 0, 'rlist': "fsssfaf", "blist": "23323"}

    return render(request, 'domainManager/admin.html', {"d": json.dumps(data, ensure_ascii=False)})


@csrf_exempt
def get_domainDateList(request):
    page = request.POST.get('page')
    rows = request.POST.get('limit')
    # print("-----------")
    # print(page)
    # print(rows)

    i = (int(page) - 1) * int(rows)
    j = (int(page) - 1) * int(rows) + int(rows)

    domainDates = DomainDate.objects.all()
    total = domainDates.count()
    dates = domainDates[i:j]
    resultdict = {}
    dict = []
    for p in dates:
        dic = {}
        dic['id'] = p.id
        dic['originalId'] = p.originalId
        dic['ipProtocol'] = p.ipProtocol
        dic['rootId'] = p.rootId
        dic['totDataBytes'] = p.totDataBytes
        dic['srcDataBytes'] = p.srcDataBytes
        dic['dstDataBytes'] = p.dstDataBytes
        dic['firstPacket'] = p.firstPacket
        dic['lastPacket'] = p.lastPacket
        dic['srcIp'] = p.srcIp
        dic['srcPort'] = p.srcPort
        dic['dstIp'] = p.dstIp
        dic['dstPort'] = p.dstPort
        dic['totPackets'] = p.totPackets
        dic['srcPackets'] = p.srcPackets
        dic['dstPackets'] = p.dstPackets
        dic['totBytes'] = p.totBytes
        dic['srcBytes'] = p.srcBytes
        dic['dstBytes'] = p.dstBytes
        dic['node'] = p.node
        dic['uri'] = p.uri
        dic['srcGEO'] = p.srcGEO
        dic['dstGEO'] = p.dstGEO
        dic['subject'] = p.subject
        dic['src'] = p.src
        dic['dst'] = p.dst
        dic['filename'] = p.filename
        dic['host'] = p.host
        dic['certificate'] = p.certificate
        dic['channel'] = p.channel

        dict.append(dic)
    resultdict['code'] = 0
    resultdict['msg'] = ""
    resultdict['count'] = total
    resultdict['data'] = dict
    # print(resultdict)
    return JsonResponse(resultdict, safe=False)


@csrf_exempt
def get_domainUrlList(request):
    page = request.POST.get('page')
    rows = request.POST.get('limit')
    # print("-----------")
    # print(page)
    # print(rows)

    i = (int(page) - 1) * int(rows)
    j = (int(page) - 1) * int(rows) + int(rows)

    domainUrl = DomainUrl.objects.all()
    total = domainUrl.count()
    dates = domainUrl[i:j]
    resultdict = {}
    dict = []
    for p in dates:
        dic = {}
        dic['id'] = p.id
        dic['url'] = p.url

        dict.append(dic)
    resultdict['code'] = 0
    resultdict['msg'] = ""
    resultdict['count'] = total
    resultdict['data'] = dict
    # print(resultdict)
    return JsonResponse(resultdict, safe=False)


@csrf_exempt
def uploadDomain(request):
    # print(request.FILES)
    resultdict = {}
    f = request.FILES.get('file')
    excel_type = f.name.split('.')[1]
    if excel_type in ['xlsx', 'xls']:
        # 开始解析上传的excel表格
        wb = xlrd.open_workbook(filename=None, file_contents=f.read())
        table = wb.sheets()[0]
        rows = table.nrows  # 总行数

        try:
            with transaction.atomic():  # 控制数据库事务交易
                for i in range(1, rows):
                    rowVlaues = table.row_values(i)
                    print(rowVlaues)
                    domainUrl = DomainUrl()
                    domainUrl.url = rowVlaues

                    domainUrl.save()

        except:
            logger.error('解析excel文件或者数据插入错误')
            resultdict = {"code": 1, "msg": "导入失败"}
            return JsonResponse(resultdict, safe=False)

    else:
        resultdict = {"code": 1, "msg": "导入失败"}
        return JsonResponse(resultdict, safe=False)

    resultdict = {"code": 0, "msg": "导入成功"}
    return JsonResponse(resultdict, safe=False)
